package com.ruoyi.system.outto.game.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.inter.mapper.PriceRecMapper;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.mapper.*;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/30 17:15
 */
@Service
public class CommonApiImpl implements CommonApi {

    @Resource
    private SalePartnerMapper salePartnerMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private InterNameMapper interNameMapper;
    @Resource
    private FieldConfigMapper fieldConfigMapper;

    @Resource
    private PriceRecMapper priceRecMapper;


    @Autowired
    private ISysDictDataService dictDataService;

    @Override
    public SalePartner get(String code, Long userId) {
        SuprAuth suprAuth = new SuprAuth();
        suprAuth.setSuprId(userId);

        InterName interName = new InterName();
        interName.setCode(code);
        List<InterName> interNames = interNameMapper.selectInterNameList(interName);
        if (!CollectionUtils.isEmpty(interNames)) {
            suprAuth.setSaleId(String.valueOf(interNames.get(0).getId()));
            List<SuprAuth> suprAuths = suprAuthMapper.selectSuprAuthList(suprAuth);
            if (!CollectionUtils.isEmpty(suprAuths)) {
                SalePartner salePartner = salePartnerMapper.selectSalePartnerById(suprAuths.get(0).getConfigId());
                if (!Objects.isNull(salePartner)) {
                    return salePartner;
                }
            }
        }
        return null;
    }

    @Override
    public List<String> getYDList() {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(LCConstant.saleNameYDD);
        sysDictData.setStatus(Constants.STR_0);
        List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(sysDictData);
        return sysDictDataList.stream().map(s -> s.getDictValue()).collect(Collectors.toList());
    }

    @Override
    public String getSelectLable(String type, String fildName, String labels) {

        /**
         * 1、获取游戏和字段的多选框
         * 2、循环选中标签
         */
        Set<String> resultList = new HashSet<>();
        FieldConfig fieldConfig = new FieldConfig();
        fieldConfig.setType(type);
        fieldConfig.setFieldName(fildName);
        fieldConfig.setCfgType("1");
        List<FieldConfig> fieldConfigs = fieldConfigMapper.selectFieldConfigList(fieldConfig);
        for (FieldConfig config : fieldConfigs) {
            String fieldValue = config.getFieldValue();
            if (StringUtils.isNotEmpty(fieldValue)) {
                String[] split = fieldValue.split(",");
                Arrays.asList(split).stream().forEach(s -> {
                    if (StringUtils.isNotEmpty(labels) && labels.contains(s)) {
                        resultList.add(s);
                    }
                    ;
                });
            }
        }
        return StringUtils.join(resultList.toArray(), ",");
    }

    @Override
    public BigDecimal addPrice(BigDecimal oldprice, Long discount) {
        if (Objects.nonNull(oldprice)) {
            if (Objects.isNull(discount)) {
                return oldprice;
            }
//            BigDecimal add = new BigDecimal(100).add(new BigDecimal(discount)).divide(new BigDecimal(100));
//            BigDecimal multiply = oldprice.multiply(add).setScale(0, BigDecimal.ROUND_UP);


//            BigDecimal multiply = new BigDecimal(100).subtract(new BigDecimal(discount));
//
//            BigDecimal divide = multiply.divide(new BigDecimal(100));
//
//            BigDecimal divide1 = oldprice.divide(divide, 0, BigDecimal.ROUND_UP);
            BigDecimal multiply = new BigDecimal(discount).divide(new BigDecimal(100));

            BigDecimal divide1 = oldprice.multiply(multiply);

            return divide1;
        } else {
            return new BigDecimal(0);
        }
    }

    public void setPrice(BigDecimal oldprice, Long id, SalePartner salePartner) {

//        Long seleep = salePartner.getSeleep();
//        if (seleep > 0) {
//            PriceRec priceRec = new PriceRec();
//            priceRec.setPrice(oldprice.toPlainString());
//            priceRec.setSaleCode(salePartner.getSaleName());
//            priceRec.setSaleName(salePartner.getName());
//            priceRec.setConfig(salePartner.getId());
//            priceRec.setInfoid(id);
//
//            PriceRec select = new PriceRec();
//            select.setInfoid(id);
//            select.setConfig(salePartner.getId());
//            List<PriceRec> priceRecs = priceRecMapper.selectPriceRecList(select);
//            if (!CollectionUtils.isEmpty(priceRecs)) {
//                PriceRec priceRec1 = priceRecs.get(0);
//                priceRec1.setPrice(oldprice.toPlainString());
//                priceRec1.setSaleCode(salePartner.getSaleName());
//                priceRec1.setSaleName(salePartner.getName());
//                priceRec1.setConfig(salePartner.getId());
//                priceRec1.setInfoid(id);
//                priceRecMapper.updatePriceRec(priceRec1);
//            } else {
//                priceRecMapper.insertPriceRec(priceRec);
//            }
//        }
    }


    @Override
    public String loginPanzhi(SalePartner salePartner){
        String url = "https://api.pzds.com/api/web-client/v2/user/public/login/password";
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> action = new HashMap<>();
        params.put("phone", salePartner.getSaleKey());
        String string = DigestUtils.md5Hex(salePartner.getOther());
        params.put("password", string);
        params.put("openId", null);
        params.put("thirdType", null);
        params.put("unionId", null);
        action.put("action", params);

        // 生成 随机数 并生成sign  注意 &2147483647         &accessKey=3qXyB7uf
        StringBuilder sb = new StringBuilder();
        long PZTimestamp = System.currentTimeMillis();
        String Random = getRanString();
        sb.append("PZTimestamp=");
        sb.append(PZTimestamp);
        sb.append("&Random=");
        sb.append(Random);
        sb.append("&2147483647=");
        sb.append(JSONObject.toJSON(action));
        sb.append("&accessKey=3qXyB7uf");
        String b = sb.toString();
        try {
            b = URLEncoder.encode(b, "UTF-8");
        } catch (UnsupportedEncodingException e) {
          throw new GlobalException( e.getMessage());
        }
        b = b.replace("%26", "&");
        b = b.replace("%3D", "=");
        b = b.replaceAll("\\(", "%28");
        b = b.replaceAll("\\)", "%29");
        b = b.replaceAll("'", "%27");
        b = b.replaceAll("\\*", "%2A");
        b = b.replaceAll("~", "%7E");
        b = b.replaceAll("!|！", "%21");
        String sign = DigestUtils.md5Hex(b);
        //开始拼装请求
        String body = HttpRequest.post(url).header("Accept", "application/json, text/plain, */*")
                .header("PZTimestamp", String.valueOf(PZTimestamp))
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Origin", "https://www.pzds.com")
                .header("PZPlatform", "pc")
                .header("PZVersion", "1.0.0")
                .header("PZVersionCode", "1")
                .header("Random", Random)
                .header("Referer", "https://www.pzds.com/")
                .header("sign", sign)
                .header("sec-ch-ua-mobile", "?0")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123 .0.0.0")
                .body(JSONObject.toJSONString(action)).execute().body();
        return JSONObject.parseObject(body).getString("data");
    }

    public static String getRanString() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        if (str.startsWith("0")) {
            str = str.replaceFirst("0", "1");
        }
        return str;
    }

    public static void main(String[] args) {

        Long discount = 95l;
        BigDecimal oldprice = new BigDecimal(299);


//        BigDecimal multiply = new BigDecimal(100).subtract(new BigDecimal(discount));
        BigDecimal multiply = new BigDecimal(discount).divide(new BigDecimal(100));

        BigDecimal divide1 = oldprice.multiply(multiply);

        System.out.println(divide1);

    }

}
